<!DOCTYPE html>
<html lang="zh-CN">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>主题蛋糕管理</title>
		<link rel="stylesheet" href="../layui/css/layui.css">
		<link rel="stylesheet" href="../css/index.css">
		<script src="../js/authChecker.js"></script>
		<style>
			.theme-container {
				padding: 20px;
			}

			.theme-table {
				width: 100%;
				border-collapse: collapse;
				margin-top: 20px;
			}

			.theme-table th,
			.theme-table td {
				border: 1px solid #ccc;
				padding: 10px;
				text-align: center;
			}

			.theme-table th {
				background-color: #d8d8d9;
				color: black;
				font-weight: bold;
			}

			.theme-table tr:nth-child(even) {
				background-color: #f9f9f9;
			}

			.theme-table tr:hover {
				background-color: #f1f1f1;
			}

			.theme-actions {
				display: flex;
				justify-content: center;
				gap: 10px;
			}

			.theme-form-item {
				margin-bottom: 15px;
			}

			.layui-card-header {
				font-size: 22px;
				color: #333;
				margin-bottom: 20px;
				font-weight: 600;
			}

			/* 平均分配四列宽度 */
			.theme-table th:nth-child(1),
			.theme-table td:nth-child(1) {
				width: 25%;
			}

			.theme-table th:nth-child(2),
			.theme-table td:nth-child(2) {
				width: 25%;
			}

			.theme-table th:nth-child(3),
			.theme-table td:nth-child(3) {
				width: 25%;
			}

			.theme-table th:nth-child(4),
			.theme-table td:nth-child(4) {
				width: 90%;
			}

			/* 调整按钮位置 */
			.theme-actions {
				justify-content: center;
			}

			/* 添加新主题按钮颜色 */
			#addTheme {
				background-color: #FF1493;
				color: white;
			}
		</style>
	</head>

	<body>
		<div class="theme-container">
			<div class="layui-row layui-col-space15">
				<div class="layui-col-md12">
					<div class="layui-card">
						<div class="layui-card-header">主题蛋糕管理</div>
						<div class="layui-card-body">
							<button class="layui-btn layui-btn-primary" id="addTheme">
								<i class="layui-icon">&#xe654;</i> 添加新主题
							</button>
							<button class="layui-btn layui-btn-primary" id="refreshThemes">
								<i class="layui-icon">&#x1002;</i> 刷新列表
							</button>
						</div>
					</div>
				</div>

				<!-- 主题列表表格 -->
				<table class="theme-table" id="themeTable">
					<thead>
						<tr>
							<th>主题ID</th>
							<th>主题名称</th>
							<th>主题图片</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody>
						<!-- 动态内容将通过JS填充 -->
					</tbody>
				</table>
			</div>
		</div>

		<!-- 添加主题的弹窗 -->
		<div id="addThemeDialog" style="display: none; padding: 20px;">
			<form class="layui-form" lay-filter="addThemeForm">
				<input type="hidden" name="id">
				<div class="theme-form-item">
					<label class="layui-form-label">主题名称</label>
					<div class="layui-input-block">
						<input type="text" name="themetitle" required lay-verify="required" placeholder="请输入主题名称"
							autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="theme-form-item">
					<label class="layui-form-label">主题图片</label>
					<div class="layui-input-block">
						<button type="button" class="layui-btn" id="addUploadBtn">
							<i class="layui-icon">&#xe67c;</i>上传图片
						</button>
						<div class="layui-upload-list">
							<img class="layui-upload-img" id="addPreviewImg"
								style="max-width: 100%; margin-top: 10px; display: none;">
						</div>
					</div>
				</div>
			</form>
		</div>

		<!-- 编辑主题的弹窗 -->
		<div id="editThemeDialog" style="display: none; padding: 20px;">
			<form class="layui-form" lay-filter="editThemeForm">
				<input type="hidden" name="id">
				<div class="theme-form-item">
					<label class="layui-form-label">主题名称</label>
					<div class="layui-input-block">
						<input type="text" name="themetitle" required lay-verify="required" placeholder="请输入主题名称"
							autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="theme-form-item">
					<label class="layui-form-label">主题图片</label>
					<div class="layui-input-block">
						<button type="button" class="layui-btn" id="editUploadBtn">
							<i class="layui-icon">&#xe67c;</i>上传图片
						</button>
						<div class="layui-upload-list">
							<img class="layui-upload-img" id="editPreviewImg"
								style="max-width: 100%; margin-top: 10px; display: none;">
						</div>
					</div>
				</div>
			</form>
		</div>

		<script src="../js/jquery3.5.1.js"></script>
		<script src="../layui/layui.js"></script>
		<script>
			// 在页面加载时立即检查登录状态
			if (!checkAdminLogin()) {
				// 登录检查失败，阻止页面继续加载
				console.log('登录验证失败，已跳转至登录页');
			} else {
				layui.use(['form', 'layer', 'upload'], function() {
					var form = layui.form;
					var layer = layui.layer;
					var upload = layui.upload;
					var $ = layui.$;
					// -------------------------- 新增主题状态和上传 --------------------------
					let addStatus = {
						isUploaded: false,
						imageUrl: ''
					};

					// 初始化新增上传组件
					upload.render({
						elem: '#addUploadBtn',
						url: 'http://localhost:8887/upload/themeHandle',
						size: 10240, // 10MB限制
						accept: 'images',
						acceptMime: 'image/*',
						data: {
							themetitle: function() {
								return $('#addThemeDialog input[name="themetitle"]').val();
							},
							id: ''
						},
						done: function(res) {
							if (res.code == 200) {
								$('#addPreviewImg').attr('src', res.data.url).show();
								addStatus.imageUrl = res.data.url;
								addStatus.isUploaded = true;
								layer.msg('图片上传成功', {
									icon: 1
								});
							} else {
								addStatus.isUploaded = false;
								layer.msg(res.msgerr || '上传失败', {
									icon: 2
								});
							}
						}
					});

					// -------------------------- 编辑主题状态和上传 --------------------------
					let editStatus = {
						currentId: '',
						isUploaded: false,
						imageUrl: ''
					};

					// 初始化编辑上传组件
					upload.render({
						elem: '#editUploadBtn',
						url: 'http://localhost:8887/upload/themeHandle',
						size: 10240, // 10MB限制
						accept: 'images',
						acceptMime: 'image/*',
						data: {
							themetitle: function() {
								return $('#editThemeDialog input[name="themetitle"]').val();
							},
							id: function() {
								return editStatus.currentId;
							}
						},
						done: function(res) {
							if (res.code == 200) {
								$('#editPreviewImg').attr('src', res.data.url).show();
								editStatus.imageUrl = res.data.url;
								editStatus.isUploaded = true;
								layer.msg('图片上传成功', {
									icon: 1
								});
							} else {
								editStatus.isUploaded = false;
								layer.msg(res.msgerr || '上传失败', {
									icon: 2
								});
							}
						}
					});

					// -------------------------- 功能方法 --------------------------
					// 添加主题
					$('#addTheme').on('click', function() {
						resetAddForm();
						layer.open({
							type: 1,
							title: '添加新主题',
							area: ['800px', '500px'],
							content: $('#addThemeDialog'),
							btn: ['确认添加', '取消'],
							yes: function(index) {
								var themetitle = $('#addThemeDialog input[name="themetitle"]').val()
									.trim();

								if (!themetitle) {
									layer.msg('请输入主题名称', {
										icon: 2
									});
									return;
								}

								if (!addStatus.isUploaded) {
									layer.msg('请上传图片', {
										icon: 2
									});
									return;
								}

								layer.msg('添加成功', {
									icon: 1
								});
								loadThemes();
								layer.close(index);
								resetAddForm();
							},
							cancel: function() {
								resetAddForm();
							}
						});
					});

					// 编辑主题
					function editTheme(themeId) {
						$.ajax({
							url: 'http://localhost:8887/themecake/selectById',
							type: 'GET',
							data: {
								id: themeId
							},
							success: function(res) {
								if (res.code == 200 && res.data.data) {
									var theme = res.data.data;
									editStatus.currentId = theme.id;

									form.val('editThemeForm', {
										id: theme.id,
										themetitle: theme.themetitle
									});

									if (theme.themeurl) {
										$('#editPreviewImg').attr('src', theme.themeurl).show();
										editStatus.imageUrl = theme.themeurl;
									} else {
										$('#editPreviewImg').attr('src', '').hide();
									}

									layer.open({
										type: 1,
										title: '编辑主题',
										area: ['800px', '500px'],
										content: $('#editThemeDialog'),
										btn: ['保存修改', '取消'],
										yes: function(index) {
											var themetitle = $(
													'#editThemeDialog input[name="themetitle"]')
												.val().trim();

											if (!themetitle) {
												layer.msg('请输入主题名称', {
													icon: 2
												});
												return;
											}
											layer.msg('修改成功', {
												icon: 1
											});
											loadThemes();
											layer.close(index);
										},
										cancel: function() {
											resetEditForm();
										}
									});
								}
							}
						});
					}

					// 重置表单
					function resetAddForm() {
						$('#addThemeDialog input[name="themetitle"]').val('');
						$('#addPreviewImg').attr('src', '').hide();
						addStatus = {
							isUploaded: false,
							imageUrl: ''
						};
					}

					function resetEditForm() {
						$('#editThemeDialog input[name="themetitle"]').val('');
						$('#editThemeDialog input[name="id"]').val('');
						$('#editPreviewImg').attr('src', '').hide();
						editStatus = {
							currentId: '',
							isUploaded: false,
							imageUrl: ''
						};
					}

					// 加载主题列表
					function loadThemes() {
						$.ajax({
							url: 'http://localhost:8887/themecake/selectAllTheme',
							type: 'GET',
							success: function(res) {
								if (res && res.data && res.data.themecakeList) {
									renderThemeList(res.data.themecakeList);
								} else {
									layer.msg('获取主题列表失败', {
										icon: 2
									});
								}
							},
							error: function() {
								layer.msg('网络错误，请稍后重试', {
									icon: 2
								});
							}
						});
					}

					// 渲染主题列表
					function renderThemeList(themes) {
						var html = '';
						themes.forEach(function(theme) {
							let imageUrl = theme.themeurl ? theme.themeurl : '';

							html += `
                        <tr>
                            <td>${theme.id || '未命名ID'}</td>
                            <td>${theme.themetitle || '未命名主题'}</td>
                            <td>
                                <img src="${imageUrl || '../img/default-theme.jpg'}" 
                                    onerror="this.src='../img/default-theme.jpg'" 
                                    style="max-width: 38px; max-height: 38px;">
                            </td>
                            <td class="theme-actions">
                                <button class="layui-btn layui-btn-primary edit-theme" data-id="${theme.id}">
                                    <i class="layui-icon">&#xe642;</i> 编辑
                                </button>
                                <button class="layui-btn layui-btn-primary delete-theme" data-id="${theme.id}">
                                    <i class="layui-icon">&#xe640;</i> 删除
                                </button>
                            </td>
                        </tr>
                    `;
						});
						$('#themeTable tbody').html(html);

						// 绑定编辑和删除事件
						$('.edit-theme').on('click', function() {
							var themeId = $(this).data('id');
							editTheme(themeId);
						});

						$('.delete-theme').on('click', function() {
							var themeId = $(this).data('id');
							deleteTheme(themeId);
						});
					}

					// 删除主题
					function deleteTheme(themeId) {
						layer.confirm('确定要删除这个主题吗？', {
							icon: 3,
							title: '提示'
						}, function(index) {
							$.ajax({
								url: 'http://localhost:8887/themecake/delete',
								type: 'POST',
								data: {
									id: themeId
								},
								success: function(res) {
									if (res.code == 200) {
										layer.msg('主题已删除', {
											icon: 1
										});
										loadThemes();
									} else {
										layer.msg(res.msgerr || '删除失败', {
											icon: 2
										});
									}
								},
								error: function() {
									layer.msg('删除失败，请稍后重试', {
										icon: 2
									});
								}
							});
							layer.close(index);
						});
					}

					// 刷新主题列表
					$('#refreshThemes').on('click', function() {
						loadThemes();
						layer.msg('主题列表已刷新', {
							icon: 1
						});
					});

					// 初始化加载主题列表
					loadThemes();
				});
			}
		</script>
	</body>
</html>